<template>
    <div class="bill">
      <van-field
        v-model="iccid"
        is-link
        readonly
        label="SIM卡"
        placeholder="选择已实名的SIM卡"
        @click="showPicker = true"
      />
      <van-popup v-model="showPicker" round position="bottom">
        <van-picker
          show-toolbar
          title="选择已实名的SIM卡"
          :columns="columns"
          @cancel="showPicker = false"
          @confirm="(value)=>{
          this.iccid = value
          this.showPicker = false
        }"
        />
      </van-popup>
      <van-cell-group inset style="margin-top: 20px">
        <van-cell title="卡余额" value="50元" >
          <template #default>
            <span class="moneny">{{balance}}元</span>
          </template>
        </van-cell>
      </van-cell-group>
      <h3 style="padding: 0 20px;">请选择充值金额</h3>
      <Grid :column-num="4" :border="false" :gutter="20">
        <GridItem v-for="item in moneyMap" @click="setBill(item.value)" :class="[currentBill===item.value?'active-item':'',firstBill&&item.value<50?'forbidden-item':'']" :key="item.value" :text="item.value+'元'" />
      </Grid>
      <div style="margin:40px 0;padding: 0 20px">
        <div class="tips">
          <span> 1、首次充值50后将赠送大额流量体验包 </span>
          <span>2、充值的余额可用于购买套餐流量包，可在SIM卡信息中查看 </span>
        </div>
        <van-button type="warning" style="width: 100% " @click="trade">立即支付</van-button>
      </div>
    </div>
</template>

<script>
  import {
    getCardList,
    getRecharge,
    getSimFlow,
    notifyTrade,
    payRecharge,
    postRecharge,
    rechargeCallback
  } from "../../api/user";
  import {checkSystem, urlSearch} from "../../utils";
  import { Grid, GridItem } from 'vant';
  import wx from "weixin-js-sdk";

  export default {
        name: "bill",
    components:{Grid, GridItem},
      data() {
        return {
          iccid: '',
          msisdn:'',
          simId:'',
          tradeNo:'',
          totalData:[],
          showPicker: false,
          columns: [],
          balance:0,  // 余额
          currentBill:50,
          firstBill:true, //首充开关  true 为首次
          clientIp:returnCitySN["cip"],
          moneyMap:[
            {value:5}, {value:10}, {value:20},
            {value:30}, {value:40}, {value:50},
            {value:70}, {value:100}, {value:200},
            {value:300}, {value:500},
          ],
        }
      },
    mounted() {
      this.getCardList()
    },
    beforeMount() {
      const Url = window.location.href
      let newUrl = ''
      if(Url.includes('/#/')){
        newUrl = Url.replace('#','?#')
        location.replace(newUrl)
      }
    },
    watch:{
      iccid(value){
        let msisdn = this.totalData.filter(item=>item.iccid === value)[0].msisdn
        this.msisdn = msisdn
        this.simId = this.totalData.filter(item=>item.iccid === value)[0].simId
        this.getRecharge(msisdn)
      }
    },
    methods:{
      getCardList() {
        getCardList(this.clientId).then(res => {
          this.columns = res.data.filter(item=>item.realStatus===2).map(item=>item.iccid)
          this.totalData = res.data
          this.totalCardList = res.data
          this.iccid = location.hash.split('=')[1]||this.columns[0]
        })
      },
      // 查询余额
      getRecharge(msisdn){
        // 查询余额
        getRecharge(msisdn).then(res=>{
          this.balance = res.data.balance||0
          // 判断是否首充
          if(res.data.firstStatus===1){
            this.firstBill = false
          }else this.firstBill = true
        })
      },
      setBill(bill){
        this.currentBill=bill
        console.log(bill)
      },
      async trade(){
        const reqData = {
          amount: this.currentBill/100,
          channel:1,
          iccid:this.iccid,
          msisdn:this.msisdn,
          isFirst:this.firstBill?1:0,
          payType:1,
        }
        try {
          const res = await postRecharge(reqData)
          this.tradeNo = res.data.tradeNo
          const billData = {
            clientIp:this.clientIp,
            h5Type:checkSystem(), //机型是安卓还是ios
            tradeId:res.data.id
          }
          const resPay = await payRecharge(billData)
          const payData = JSON.parse(resPay.data)

          console.log(payData)
          const {appId,timeStamp,nonceStr,signType,paySign} = payData
          const preId = payData.package
          console.log(appId)
          const _this = this
          wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: appId, // 必填，公众号的唯一标识
            jsApiList: ['chooseWXPay'], // 必填，需要使用的JS接口列表
          });
          wx.ready(function(){
            wx.chooseWXPay({
              appId:appId,
              timestamp: timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
              nonceStr: nonceStr, // 支付签名随机串，不长于 32 位
              package: preId, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
              signType: signType, // 微信支付V3的传入RSA,微信支付V2的传入格式与V2统一下单的签名格式保持一致
              paySign: paySign, // 支付签名
              success: async function (res) {
                // 支付成功后的回调函数
                // await rechargeCallback(this.tradeNo)
                location.href = '/wexin/#/home'
              }
            });
          });

        }catch (e) {
          console.log(e)
        }

      }
    }
    }
</script>
<style lang="scss">
  .bill{
    .van-grid-item__content--center{
      border: 1px solid #07c160;
      border-radius: 5px;
      span{
        color: #07c160;
      }
      &:hover{
        background: #07c160;
        span{
          color: #fff;
        }
      }
    }
    .active-item{
      .van-grid-item__content--center{
        background: #07c160;
        span{
          color: #fff;
        }
      }
    }
    .forbidden-item{
      pointer-events: none;
      cursor: default;
      opacity: 0.5;
    }
  }
</style>
<style scoped>
.moneny{
  color: #ff976a;
  font-weight: 600;
  font-size: 20px;
}
.tips{
  display: flex;
  flex-direction: column;
  margin-bottom: 5px;
  color: #969799;
}
</style>
